const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

const ballRadius = 10;
let ballX = canvas.width / 2;
let ballY = canvas.height / 2;

const speed = 10;

const ws = new WebSocket('ws://127.0.0.1:20001');

nickname = "";
islogin = false
ws.onopen = function() {
    console.log("连接成功");
};

ws.onmessage = function(evt) {
    console.log("接收到消息：" + evt.data);
    m = evt.data // pp|wangyichen|#307aa2|w|78*90
    //|分割字符串
    cmdArr = m.split("|");
    console.log(cmdArr);
    cmd = cmdArr[0];
    if (cmd == "pp") {
        nk = cmdArr[1];
        ballcolor = cmdArr[2];
        action = cmdArr[3];
        pos = cmdArr[4];
        xy = pos.split("*");
        x = parseInt(xy[0]);
        y = parseInt(xy[1]);
        
        ballSingle = {
            x: x,
            y: y,
            radius: 10,
            color: ballcolor,
        };
        balls.set(nk, ballSingle);
        //balls[nickname] = ballSingle;
    }
};

ws.onclose = function() {
    console.log("连接关闭");
};

$("#login").click(function() {
    nickname = $("#nickname").val();
    if (nickname == "") {
        alert("请输入昵称");
        return;
    }
    //随机一个颜色
    myselfBall.color = "#" + Math.floor(Math.random() * 0xffffff).toString(16);

    //balls[nickname] = myselfBall
    balls.set(nickname, myselfBall);
    islogin = true;
    console.log("li|" + nickname, myselfBall.color);
    ws.send("li|" + nickname);
});

$("#logout").click(function() {
    nickname = $("#nickname").val();
    if (nickname == "") {
        alert("请输入昵称");
        return;
    }
    islogin = false;
    console.log("lo|" + nickname);
    ws.send("lo|" + nickname);
    ws.close();
});

const myselfBall = {
    x: canvas.width / 2,
    y: canvas.height / 2,
    radius: 10,
    color: 'white',
};

let direction = { x: 0, y: 0 };

//balls 类型map 保存所有的球 key是昵称 value是球的信息

const balls = new Map();




function drawBall() {
    //遍历balls map

    if (balls.size == 0) {
        return;
    }
    console.log("====balls===", balls);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    for (let [nk, thisBall] of balls) {
        //console.log("====color===", thisBall.color)
        ctx.beginPath();
        ctx.arc(thisBall.x, thisBall.y, thisBall.radius, 0, Math.PI * 2);
        ctx.fillStyle = thisBall.color;
        ctx.fill();
        ctx.closePath();

        ctx.font = "10px Arial";
        ctx.fillStyle = "black";
        //居中显示
        ctx.textAlign = "center";
        ctx.fillText(nk, thisBall.x - 10, thisBall.y - 15);
    }
}

function updatePosition() {
   // Update the position of the ball based on direction and speed
   myselfBall.x += direction.x * speed;
   myselfBall.y += direction.y * speed;

   // Ensure the ball does not go out of bounds
   if (myselfBall.x - myselfBall.radius < 0) {
    myselfBall.x = myselfBall.radius;
   } else if (myselfBall.x + myselfBall.radius > canvas.width) {
    myselfBall.x = canvas.width - myselfBall.radius;
   }

   if (myselfBall.y   - myselfBall.radius < 0) {
    myselfBall.y = myselfBall.radius;
   } else if (myselfBall.y + myselfBall.radius > canvas.height) {
    myselfBall.y = canvas.height - myselfBall.radius;
   }

   drawBall();


   const positionMessage = "pp|" + nickname + "|" + myselfBall.color + "|" + "w" + "|" + myselfBall.x + "*" + myselfBall.y;
    
    // Only send message if WebSocket is open
    if (ws.readyState === WebSocket.OPEN && islogin && nickname != "") {
        ws.send(positionMessage);
        //console.log(`Sent position: ${positionMessage}`);
    }

   // Send the position to the WebSocket server at a rate of 15 frames per second
//    if (ws.readyState === WebSocket.OPEN) {
//        ws.send(JSON.stringify({ x: ball.x, y: ball.y }));
//    }
}

function handleKeyDown(event) {
     switch(event.key.toLowerCase()) {
         case 'w':
             direction.y = -1; break; // Move up
         case 'a':
             direction.x = -1; break; // Move left
         case 's':
             direction.y=1 ; break; // Move down 
         case'd':
             direction.x=1 ; break; // Move right 
     }
}
function handleKeyUp(event){
     switch(event.key.toLowerCase()) { 
         case'w': 
         case's':
              direction .y=0 ; break ;
         case'a': 
         case'd': 
              direction .x=0 ; break ;
     }
}
document.addEventListener ('keydown' ,handleKeyDown ) ;
document.addEventListener ('keyup' ,handleKeyUp ) ;

setInterval(updatePosition ,1000/15 );// Update position at a rate of15 frames per second

drawBall();// Initial drawing of the Ball and Nickname